<?php
namespace app\api\controller\attachment;


use app\api\controller\Api;
use app\common\system\model\AttachmentCategory;
use app\common\system\validate\AttachmentCategoryValidate;
use think\db\exception\DbException;

class Category extends Api
{
    public function getTree()
    {
        $model = new AttachmentCategory();
        $list = $model->column('id,parent_id,title', 'id');
        $tree = build_tree([], $list, 0);

        $result['tree'] = $tree;
        return success($result, '获取数据成功');
    }

    // 创建信息
    public function create()
    {
        $post = $this->request->post();
        // 创建的时候清除干扰的信息
        unset($post['id']);

        // 验证提交的数据
        $validate = new AttachmentCategoryValidate();
        if (!$validate->scene('create')->check($post)) return error([], $validate->getError());

        $model = new AttachmentCategory();
        try {
            $model->save($post);
            return success([], '添加成功');
        } catch (DbException $e) {
            return error([], '添加失败');
        }
    }

    // 编辑信息
    public function save()
    {
        $post = $this->request->post();
        // 验证提交的数据
        $validate = new AttachmentCategoryValidate();
        if (!$validate->scene('edit')->check($post)) return error([], $validate->getError());

        $model = new AttachmentCategory();
        $row = $model->where('id', $post['id'])->find();

        try {
            $row->save($post);
            return success([], '编辑成功');

        } catch (DbException $e) {

            return error([], $e->getMessage());
        }
    }

    // 删除
    public function delete()
    {
        $post = $this->request->post();
        if (empty($post['id'])) return error([], '参数错误');
        // 获取当前删除的编号
        $model = new AttachmentCategory();
        $row = $model->where('id', $post['id'])->find();
        if (empty($row)) return error([], '该数据已不存在');

        // 获取当前的子
        $children = $model->where('parent_id', $post['id'])->find();
        if (empty($children)) {
            try {
                $row->delete();
                return success([], '删除成功');
            } catch (DbException $e) {
                return error([], $e->getMessage());
            }
        } else { // 如果存在子不能执行删除
            return error([], '请先删除子数据');
        }
    }
}